package com.iRomantic.controller.app;

import java.io.File;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.iRomantic.common.AppJsonResponse;
import com.iRomantic.common.BaseController;
import com.iRomantic.common.oss.OSSService;
import com.iRomantic.common.util.FileUtil;
import com.iRomantic.config.Constant;
import com.iRomantic.domain.entity.User;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.upload.UploadFile;

public class UserAPPController extends BaseController {
	
	private static final Logger logger = LoggerFactory.getLogger(UserAPPController.class);
	
	/**
	 * 登陆
	 */
	public void login(){
		AppJsonResponse jsonResult = this.createAppJsonResponse();
		try{
			User user = getModel(User.class);
			user = user.findBySimId(user.getStr("simId"));
			if(user!=null){
				user.setUserProjectPath(user);
				jsonResult.setResult(user);
			}else{
				jsonResult.failed("用户不存在");
			}
		}catch(Exception e){
			e.getStackTrace();
			jsonResult.error(e.getMessage());
		}
		renderJson(jsonResult);
	}
	
	/**
	 * 注册
	 * @throws Exception 
	 */
	public void regist() throws Exception{
		String path = this.getSession().getServletContext().getRealPath(Constant.TEMP_FOLDER);
		UploadFile file = this.getFile("file",path);
		AppJsonResponse jsonResult = this.createAppJsonResponse();
		User user = getModel(User.class);
			
		if(file!=null){
			String fileName = FileUtil.randomFileName(file.getFileName());
			fileName = iosPictureHandler(fileName);
			user.set("pictureUrl", fileName);
			OSSService.getInstance().save(Constant.USER_PICTURE+fileName, file.getFile());
			file.getFile().delete();
		}
			
		boolean result = user.save();
		if(result==true){
			jsonResult.success("成功");
			user.setUserProjectPath(user);
			jsonResult.setResult(user);
		}else{
			jsonResult.error("失败");
		}
		
		renderJson(jsonResult);
	}
	
	public void update() throws Exception{
		String path = this.getSession().getServletContext().getRealPath(Constant.TEMP_FOLDER);
		UploadFile file = this.getFile("file",path);
		AppJsonResponse jsonResult = this.createAppJsonResponse();
		User user = getModel(User.class);
		User oldUser = User.DAO.findById(user.getStr("id"));
		if(file!=null){
			String fileName = FileUtil.randomFileName(file.getFileName());
			fileName = iosPictureHandler(fileName);
			user.set("pictureUrl", fileName);
			OSSService.getInstance().save(Constant.USER_PICTURE+fileName, file.getFile());
			file.getFile().delete();
		}
		
		boolean result = user.update();
		
		if(file!=null){
			OSSService.getInstance().deleteObject(Constant.USER_PICTURE+oldUser.getStr("pictureUrl"));
		}
		
		if(result==true){
			user = user.findById(user.getStr("id"));
			user.setUserProjectPath(user);
			jsonResult.success("成功");
			jsonResult.setResult(user);
		}else{
			jsonResult.error("失败");
		}
		renderJson(jsonResult);
	}

}
